package cn.sxt.wapperclass;

/**
 * 测试不可变字符串与可变字符串的陷阱
 */
public class TestStringBuilder3 {
    public static void main(String[] args){
        /**使用String进行字符串的拼接*/
        String str8 = "";
        //本质上使用StringBuilder拼接,但是每次循环都会生成一个StringBuildeer对象
        //获取系统剩余内存空间
        long num1 = Runtime.getRuntime().freeMemory();
        //获取系统的当前时间
        long time1 = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            str8 += i;
        }
        long num2 = Runtime.getRuntime().freeMemory();
        long time2 = System.currentTimeMillis();
        System.out.println("String占用的内存："+(num2-num1));
        System.out.println("String占用的时间："+(time2-time1));

        StringBuilder stringBuilder = new StringBuilder();
        //获取系统剩余空间
        long num3 = Runtime.getRuntime().freeMemory();
        long time3 = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            stringBuilder.append(i);
        }
        long num4 = Runtime.getRuntime().freeMemory();
        long time4 = System.currentTimeMillis();
        System.out.println("StringBuilder占用的内存："+(num4-num3));
        System.out.println("StringBuilder占用的时间："+(time4-time3));

    }
}
